"""消息仓库类"""

from typing import Optional, List, Dict, Any
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import and_, or_, desc, asc
from .base import BaseRepository
from app.models.database.message import Message
import uuid


class MessageRepository(BaseRepository[Message]):
    """消息数据访问仓库"""
    
    def __init__(self, db: Session):
        super().__init__(db, Message)
    
    def create_message(self, message_id: Optional[str] = None, conversation_id: str = "",
                      role: str = "", content: str = "", model_name: Optional[str] = None,
                      temperature: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> Message:
        """创建新消息"""
        message = Message(
            message_id=message_id or str(uuid.uuid4()),
            conversation_id=conversation_id,
            role=role,
            content=content,
            model_name=model_name,
            temperature=temperature,
            feedback=0
        )
        
        if metadata:
            message.set_metadata(metadata)
        
        self.db.add(message)
        self.db.commit()
        self.db.refresh(message)
        return message
    
    def get_by_message_id(self, message_id: str) -> Optional[Message]:
        """根据message_id获取消息"""
        return self.get_one_by_filter(message_id=message_id)
    
    def get_conversation_messages(self, conversation_id: str, skip: int = 0, limit: int = 100) -> List[Message]:
        """获取对话的所有消息"""
        return (
            self.db.query(Message)
            .filter(Message.conversation_id == conversation_id)
            .order_by(asc(Message.created_at))
            .offset(skip)
            .limit(limit)
            .all()
        )
    
    def get_recent_messages(self, conversation_id: str, limit: int = 10) -> List[Message]:
        """获取对话的最近消息"""
        return (
            self.db.query(Message)
            .filter(Message.conversation_id == conversation_id)
            .order_by(desc(Message.created_at))
            .limit(limit)
            .all()
        )
    
    def get_user_messages(self, conversation_id: str) -> List[Message]:
        """获取用户消息"""
        return self.get_by_filter(conversation_id=conversation_id, role="user")
    
    def get_assistant_messages(self, conversation_id: str) -> List[Message]:
        """获取助手消息"""
        return self.get_by_filter(conversation_id=conversation_id, role="assistant")
    
    def get_messages_with_feedback(self, conversation_id: str, feedback: int) -> List[Message]:
        """获取有特定反馈的消息"""
        return self.get_by_filter(conversation_id=conversation_id, feedback=feedback)
    
    def get_positive_feedback_messages(self, conversation_id: str) -> List[Message]:
        """获取正面反馈的消息"""
        return self.get_messages_with_feedback(conversation_id, 1)
    
    def get_negative_feedback_messages(self, conversation_id: str) -> List[Message]:
        """获取负面反馈的消息"""
        return self.get_messages_with_feedback(conversation_id, -1)
    
    def update_message_feedback(self, message_id: str, feedback: int) -> Optional[Message]:
        """更新消息反馈"""
        message = self.get_by_message_id(message_id)
        if message:
            return self.update(message, feedback=feedback)
        return None
    
    def update_message_content(self, message_id: str, content: str) -> Optional[Message]:
        """更新消息内容"""
        message = self.get_by_message_id(message_id)
        if message:
            return self.update(message, content=content)
        return None
    
    def update_message_metadata(self, message_id: str, metadata: Dict[str, Any]) -> Optional[Message]:
        """更新消息元数据"""
        message = self.get_by_message_id(message_id)
        if message:
            message.set_metadata(metadata)
            self.db.commit()
            self.db.refresh(message)
            return message
        return None
    
    def search_messages(self, query: str, conversation_id: Optional[str] = None,
                       skip: int = 0, limit: int = 100) -> List[Message]:
        """搜索消息内容"""
        db_query = self.db.query(Message).filter(
            Message.content.ilike(f"%{query}%")
        )
        
        if conversation_id:
            db_query = db_query.filter(Message.conversation_id == conversation_id)
        
        return db_query.offset(skip).limit(limit).all()
    
    def get_messages_by_model(self, model_name: str, skip: int = 0, limit: int = 100) -> List[Message]:
        """根据模型名称获取消息"""
        return (
            self.db.query(Message)
            .filter(Message.model_name == model_name)
            .offset(skip)
            .limit(limit)
            .all()
        )
    
    def get_conversation_message_count(self, conversation_id: str) -> int:
        """获取对话消息数量"""
        return self.count(conversation_id=conversation_id)
    
    def get_conversation_message_stats(self, conversation_id: str) -> Dict[str, Any]:
        """获取对话消息统计"""
        messages = self.get_conversation_messages(conversation_id)
        
        user_count = len([m for m in messages if m.role == "user"])
        assistant_count = len([m for m in messages if m.role == "assistant"])
        
        positive_feedback = len([m for m in messages if m.feedback == 1])
        negative_feedback = len([m for m in messages if m.feedback == -1])
        neutral_feedback = len([m for m in messages if m.feedback == 0])
        
        # 计算平均内容长度
        total_length = sum(len(m.content) for m in messages)
        avg_length = total_length / len(messages) if messages else 0
        
        # 统计使用的模型
        models = {}
        for message in messages:
            if message.model_name:
                models[message.model_name] = models.get(message.model_name, 0) + 1
        
        return {
            "conversation_id": conversation_id,
            "total_messages": len(messages),
            "user_messages": user_count,
            "assistant_messages": assistant_count,
            "positive_feedback": positive_feedback,
            "negative_feedback": negative_feedback,
            "neutral_feedback": neutral_feedback,
            "average_content_length": avg_length,
            "models_used": models,
            "first_message_at": messages[0].created_at.isoformat() if messages else None,
            "last_message_at": messages[-1].created_at.isoformat() if messages else None
        }
    
    def get_chat_history_format(self, conversation_id: str, limit: int = 20) -> List[Dict[str, Any]]:
        """获取聊天历史格式"""
        messages = self.get_recent_messages(conversation_id, limit)
        messages.reverse()  # 按时间正序排列
        
        return [message.to_chat_format() for message in messages]
    
    def delete_conversation_messages(self, conversation_id: str) -> int:
        """删除对话的所有消息"""
        messages = self.get_conversation_messages(conversation_id)
        count = len(messages)
        
        for message in messages:
            self.db.delete(message)
        
        self.db.commit()
        return count
    
    def get_messages_by_date_range(self, conversation_id: str, start_date, end_date) -> List[Message]:
        """根据日期范围获取消息"""
        return (
            self.db.query(Message)
            .filter(
                and_(
                    Message.conversation_id == conversation_id,
                    Message.created_at >= start_date,
                    Message.created_at <= end_date
                )
            )
            .order_by(asc(Message.created_at))
            .all()
        )
